package com.heima.wemedia.service.impl;

import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.heima.common.redis.CacheService;
import com.heima.model.common.dtos.PageResponseResult;
import com.heima.model.common.dtos.ResponseResult;
import com.heima.model.common.enums.AppHttpCodeEnum;
import com.heima.model.wemedia.dtos.ChannerlDto;
import com.heima.model.wemedia.pojos.WmChannel;
import com.heima.wemedia.mapper.WmChannelMapper;
import com.heima.wemedia.service.WmChannelService;
import io.swagger.models.auth.In;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.List;
import java.util.Set;

@Service
@Transactional
@Slf4j
public class WmChannelServiceImpl extends ServiceImpl<WmChannelMapper, WmChannel> implements WmChannelService {
    @Autowired
    private WmChannelMapper wmChannelMapper;

    @Autowired
    private CacheService cacheService;


    /**
     * 查询全部频道
     * @return
     */
    @Override
    public List<WmChannel> selectChannel() {
        List<WmChannel> list = list(Wrappers.<WmChannel>lambdaQuery().eq(WmChannel::getStatus, 1));
        return list;
    }

    /**
     * 删除频道
     *
     * @param id
     * @return
     */
    @Override
    public ResponseResult delete(Integer id) {
        //检查参数
        //设置redis中的key：wm_channel_list
        String key="wm_channel_list";
        //清空缓存中数据
        cacheService.delete(key);
        //判断id是否为null
        if (id == null) {
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_INVALID);
        }
        //查询频道
        WmChannel wmChannel = getById(id);
        if (wmChannel == null) {
            return ResponseResult.errorResult(AppHttpCodeEnum.DATA_NOT_EXIST);
        }
        //判断频道是否有效
        if (wmChannel.getStatus()) {
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_INVALID, "频道生效中，不能删除");

        }
        //删除
        removeById(id);
        return ResponseResult.errorResult(AppHttpCodeEnum.SUCCESS);
    }

    /**
     * 频道名称模糊分页查询
     *
     * @param dto
     * @return
     */
    @Override
    public ResponseResult findByNamePage(ChannerlDto dto) {
        //分页
        dto.checkParam();
        //模糊查询，分页
        Page page = new Page(dto.getPage(), dto.getSize());


        //频道名模糊查询
        // 创建LambdaQueryWrapper对象来构建查询条件
        LambdaQueryWrapper<WmChannel> lambdaQueryWrapper = new LambdaQueryWrapper<>();

        // 检查传入的dto对象的名称是否不为空或不为空字符串
        if (StringUtils.isNoneBlank(dto.getName())) {
            // 使用like方法添加一个查询条件：根据WmChannel对象的名称字段，模糊匹配dto对象中的名称值
            lambdaQueryWrapper.like(WmChannel::getName, dto.getName());
        }
        // 执行数据库分页查询，将查询结果赋值给page对象
        page = page(page, lambdaQueryWrapper);
        //返回查询的数据
        ResponseResult responseResult = new PageResponseResult(dto.getPage(), dto.getSize(), (int) page.getTotal());
        responseResult.setData(page.getRecords());
        return responseResult;
    }

    /**
     * 新增频道管理
     *
     * @param wmChannel
     * @return
     */
    @Override
    public ResponseResult saveChannel(WmChannel wmChannel) {
        //1.参数校验
        if (wmChannel == null) {
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_INVALID);
        }
        //2.判断当前频道名是否存在
        String ChannelName = wmChannel.getName();
        Integer count = wmChannelMapper.selectChannelName(ChannelName);
        if (count > 0) {
            return ResponseResult.errorResult(500, "频道已存在");
        } else {
            wmChannel.setCreatedTime(new Date());
            wmChannel.setIsDefault(true);
            save(wmChannel);
            //清理缓存
            cacheService.delete("wm_channel_list");
            saveRedis();
            // 使用String的join()方法将列表转换为字符串
            return ResponseResult.okResult(200);
        }
    }

    /**
     * 修改频道
     *
     * @param wmChannel
     * @return
     */
    @Override
    public ResponseResult updateChannel(WmChannel wmChannel) {
        //1.参数校验
        if (wmChannel == null || StringUtils.isBlank(wmChannel.getName())) {
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_REQUIRE);
        }
        //清理缓存
        cacheService.delete("wm_channel_list");
        //2.修改频道
        //2.1校验修改后的频道名称是否存在
        String ChannelName = wmChannel.getName();
        Integer count = wmChannelMapper.selectChannelName(ChannelName);
        Integer id = wmChannelMapper.selectId(ChannelName);
        //如果频道数量为0，则当前数据库内不存在此频道，可直接修改
        if (count == 0) {
            updateById(wmChannel);
            saveRedis();
        } else if (count == 1) {
            //如果数据库内只存在一个频道名称，则该名称有可能是此频道
            if (id == wmChannel.getId()) {
                updateById(wmChannel);
                saveRedis();
            } else {
                return ResponseResult.errorResult(500, "该频道已经被引用，请重新输入");
            }
        } else {
            return ResponseResult.errorResult(AppHttpCodeEnum.SERVER_ERROR);
        }
        return ResponseResult.okResult(wmChannel);
    }




    /**
     * 新增缓存
     */
    public void saveRedis() {
        List<WmChannel> list = list(Wrappers.<WmChannel>lambdaQuery().eq(WmChannel::getStatus, 1));
        for (WmChannel channel : list) {
            cacheService.lLeftPush("wm_channel_list", JSON.toJSONString(channel));
        }
    }
}